package alibaba.client.cli;

import org.apache.commons.cli.Option;

/* Improved option builder instead of the static one apache-cli provides */
public class OptionBuilder {

    private String opt;
    private String longopt;
    private String description;
    private String argName;
    private boolean required;
    private int numberOfArgs;
    private Object type;
    private boolean optionalArg;
    private char valuesep;

    public OptionBuilder() {
        reset();
    }
    
    private void reset() {
        opt = null;
        longopt = null;
        description = null;
        argName = "arg";
        type = null;
        required = false;
        numberOfArgs = 0;
        optionalArg = false;
        valuesep = (char) 0; 
    }
    
    public OptionBuilder shortOption(String newOpt) {
        opt = newOpt;
        return this;
    }
    
    public OptionBuilder longOption(String newLongopt) {
        longopt = newLongopt;
        return this;
    }

    public OptionBuilder argumentName(String name) {
        argName = name;
        return this;
    }

    public OptionBuilder valueSeparator(char sep) {
        valuesep = sep;
        return this;
    }

    public OptionBuilder required(boolean newRequired) {
        required = newRequired;
        return this;
    }

    public OptionBuilder numberOfArguments(int num) {
        numberOfArgs = num;
        return this;
    }

    public OptionBuilder optionalArguments(boolean optional) {
        optionalArg = optional;
        return this;
    }

    public OptionBuilder type(Object newType) {
        type = newType;
        return this;
    }

    public OptionBuilder description(String newDescription) {
        description = newDescription;
        return this;
    }

    public Option create() throws IllegalArgumentException {
        try {
            if (opt == null && longopt == null) {
                throw new IllegalArgumentException("Must enter at least opt or longopt");
            }
            
            Option option = new Option(opt, description);
            option.setLongOpt(longopt);
            option.setRequired(required);
            option.setOptionalArg(optionalArg);
            option.setArgs(numberOfArgs);
            option.setType(type);
            option.setValueSeparator(valuesep);
            option.setArgName(argName);
            return option;
        } finally {
            reset();
        }
    }
}
